package com.yantong.service.impl;

import com.yantong.service.IndexService;
import com.yantong.pojo.vo.DataCenterVo;
import com.yantong.utils.DateUtils;
import com.yantong.mapper.OrderMapper;
import com.yantong.mapper.OrderProductMapper;
import com.yantong.pojo.TradeConfig;
import com.yantong.service.ConfigService;
import com.yantong.mapper.MemberMapper;
import com.yantong.utils.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import static com.yantong.utils.DateUtils.getDateStartTime;

/**
 * @author kanghaixin
 * @date 2018/10/11.20:59
 */
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private ConfigService configService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;




    @Override
    public Map<String, Object> getDataCenter(Long centreId) {
        HashMap<String,Object> map = new HashMap<>();

        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
        ca.setTime(new Date()); //设置时间为当前时间
        Date lastMonth = ca.getTime(); //结果
        ca.add(Calendar.DATE, -1);//前一天

         int orderNum = orderMapper.getCentreOrderNum(centreId);//总订单数
         int lastDayOrderNum = orderMapper.getLastDayCentreOrderNum(centreId, DateUtil.getLastDay());//获取前一天总订单数
        if(lastDayOrderNum != 0){
            //今日和昨日相比订单总和比例
            double orderRate = (new BigDecimal(orderNum).subtract(new BigDecimal(orderNum).subtract(new BigDecimal(lastDayOrderNum)))).divide((new BigDecimal(orderNum).subtract(new BigDecimal(lastDayOrderNum))),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("orderRate",orderRate);//今日和昨日相比订单总和比例
        }else{
            map.put("orderRate",0d);//今日和昨日相比订单总和比例
        }
         map.put("orderNum",orderNum);//总订单数
         map.put("lastDayOrderNum",lastDayOrderNum);//获取前一天总订单数


        Double orderpriceSum = orderMapper.getCentreOrderSum(centreId);//总订单金额
        Double lastDayOrderpriceSum = orderMapper.getLastDayCentreOrderSum(centreId,DateUtil.getLastDay());//获取前一天总订单金额
        if(lastDayOrderpriceSum != null&&lastDayOrderpriceSum != 0d){
            //今日和昨日相比订单金额的比例
            double orderpriceRate = (new BigDecimal(orderpriceSum).subtract(new BigDecimal(orderpriceSum).subtract(new BigDecimal(lastDayOrderpriceSum)))).divide((new BigDecimal(orderpriceSum).subtract(new BigDecimal(lastDayOrderpriceSum))),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("orderpriceRate",orderpriceRate);//今日和昨日相比订单金额的比例
        }else{
            map.put("orderpriceRate",0d);//今日和昨日相比订单金额的比例
        }
        map.put("orderpriceSum",orderpriceSum);//总订单金额
        map.put("lastDayOrderpriceSum",lastDayOrderpriceSum);//获取前一天总订单金额


        int unpaidOrderNum = orderMapper.getUnpaidCentreOrderNum(centreId);//未支付总订单数
        int unpaidLastDayOrderNum = orderMapper.getUnpaidLastDayCentreOrderNum(centreId,DateUtil.getLastDay());//获取前一天未支付总订单数

        if(unpaidLastDayOrderNum != 0){
            //今日和昨日相比未支付订单总和比例
            double unpaidOrderRate = (new BigDecimal(unpaidOrderNum).subtract(new BigDecimal(unpaidOrderNum).subtract(new BigDecimal(unpaidLastDayOrderNum)))).divide(new BigDecimal(unpaidOrderNum).subtract(new BigDecimal(unpaidLastDayOrderNum)),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("unpaidOrderRate",unpaidOrderRate);//今日和昨日相比未支付订单总和比例
        }else{
            map.put("unpaidOrderRate",0d);//今日和昨日相比未支付订单总和比例
        }

        map.put("unpaidOrderNum",unpaidOrderNum);//未支付总订单数
        map.put("unpaidLastDayOrderNum",unpaidLastDayOrderNum);//获取前一天未支付总订单数


        return map;
    }

    @Override
    public List<DataCenterVo> getMonthOrderSumList(Long centreId, String payTime) {
        String a = payTime.substring(0,4);
        String b = payTime.substring(5,7);
        String payTimeStart = DateUtil.getFirstDayOfMonth1(Integer.parseInt(a),Integer.parseInt(b));
        String payTimeEnd = DateUtil.getLastDayOfMonth1(Integer.parseInt(a),Integer.parseInt(b));
        return  orderMapper.getMonthOrderSumList(centreId,payTimeStart,payTimeEnd);
    }


    @Override
    public Map<String,Object> getTopOrderProduct(Long centreId, String payTime) {
        HashMap<String,Object> map = new HashMap<>();
        map.put("fourOrderProductList",orderProductMapper.getFourOrderProduct(payTime,centreId)); //前四商品
        map.put("monthProductSum",orderMapper.getMonthProductSum(centreId,payTime)); //月销售总额
        return map;
    }

    @Override
    public List<DataCenterVo> getYearOrderSumList(Long centreId, String payTimeStart, String payTimeEnd) {
        return orderMapper.getYearOrderSumList(centreId,payTimeStart,payTimeEnd);
    }


    @Override
    public Map<String, Object> getIndexBaseInfo(Long centreId) {
        HashMap<String,Object> map = new HashMap<>(5);
        int startH = 20, startM = 30, endH = 20, endM = 0;
        TradeConfig config = configService.getTradeConfig(centreId);
        if (config != null) {
            startH = config.getNodeHour() == null ? startH : config.getNodeHour();
            startM = config.getNodeMin() == null ? startM : config.getNodeMin();
            endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
            endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
        }
        Date start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
        Date end = DateUtils.getAppointTime(new Date(), endH, endM);
        //今日单量
        map.put("todayOrder", orderProductMapper.countByTime(start, end, centreId));
        //今日商品量
        map.put("todayProductNums", orderProductMapper.countProductNums(start, end, centreId));
        //总拜访会员数
//        int accessTotal = accessLogMapper.countLog(null, null,centreId);
        map.put("accessTotal", 5000);

        //总单量
        map.put("orderTotal", orderProductMapper.countByTime(null, null, centreId));
        //今日拜访会员数
//        int todayAccessTotal = accessLogMapper.countLog(start, end, centreId);
        map.put("todayAccessTotal", 2000);
        //总下单会员数
        int orderMidTotal = orderMapper.countMidByTime(null, null, centreId);
        map.put("orderMidTotal", orderMidTotal);

        //今日新增会员
        map.put("todayNewMember", memberMapper.countNewByTime(start, end, centreId));
        //今日下单会员数
        int todayOrderMid = orderMapper.countMidByTime(start, end,centreId);
        map.put("todayOrderMid", todayOrderMid);

        //总下单比率
        BigDecimal orderRate = new BigDecimal(0);
//        if (accessTotal != 0) {
//            orderRate = new BigDecimal(orderMidTotal).divide(new BigDecimal(accessTotal),2,BigDecimal.ROUND_HALF_UP)
//                    .multiply(BigDecimal.valueOf(100));
//        }
        map.put("orderRate", 50 + "%");

        //总会员数
        map.put("totalMember", memberMapper.countNewByTime(null, null, centreId));

        //今日下单比率
        BigDecimal todayOrderRate = new BigDecimal(0);
//        if (todayAccessTotal != 0) {
//            todayOrderRate = new BigDecimal(todayOrderMid).divide(new BigDecimal(todayAccessTotal),2,BigDecimal.ROUND_HALF_UP)
//                    .multiply(BigDecimal.valueOf(100));
//        }
        map.put("todayOrderRate", todayOrderRate + "%");
        //今日下单总金额
        map.put("todayOrderPrice", orderMapper.countPriceByTime(start, end, centreId));
        return map;
    }

    @Override
    public Map<String, Object> getMemberTrend(Long centreId) {
        Calendar calendar = Calendar.getInstance();
        Date end = DateUtils.getDateEndTime(calendar.getTime());

        int max  = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DAY_OF_MONTH, - max);
        Date start = getDateStartTime(calendar.getTime());

        List<Map<String,Object>> trendList = memberMapper.getMemberTrend(start, end, centreId);
        Map<String,Object> dateNumMap = new HashMap<>(32);
        if (CollectionUtils.isNotEmpty(trendList)) {
            for (Map<String,Object> item: trendList) {
                dateNumMap.put((String) item.get("createDate"), item.get("num"));
            }
        }

        List<String> days = new ArrayList<>();
        List<Long> newMembers = new ArrayList<>();
        int index = 0;
        while (index < calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            String day = DateUtils.format(calendar.getTime());
            days.add(day);

            if (dateNumMap.get(day) != null) {
                newMembers.add((Long) dateNumMap.getOrDefault(day,0L));
            }else {
                newMembers.add(0L);
            }
            index ++;
        }
        Map<String,Object> result = new HashMap<>(4);
        result.put("centreId", centreId);
        result.put("days", days);
        result.put("newMembers", newMembers);
        return result;
    }

    @Override
    public Map<String, Object> getCumulateMemberTrend(Long centreId) {
        Calendar calendar = Calendar.getInstance();

        int max  = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DAY_OF_MONTH, - max);

        List<String> days = new ArrayList<>();
        List<Integer> memberNums = new ArrayList<>();

        int index = 0;
        while (index < calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            days.add(DateUtils.format(calendar.getTime()));
            memberNums.add(memberMapper.countNewByTime(null, DateUtils.getDateEndTime(calendar.getTime()), centreId));
            index ++;
        }
        Map<String,Object> result = new HashMap<>(4);
        result.put("centreId", centreId);
        result.put("days", days);
        result.put("memberNums", memberNums);
        return result;
    }

    @Override
    public Map<String, Object> getMemberActionTrend(Long centreId, Date targetDate) {
        Calendar calendar = Calendar.getInstance();
        Date startTime = DateUtils.getDateStartTime(targetDate);
        Date endTime = DateUtils.getDateEndTime(targetDate);
        calendar.setTime(startTime);

        List<String> hList = new ArrayList<>();
        List<Long> nList = new ArrayList<>();

        List<Map<String,Object>> list = orderMapper.getMemberActionTrend(startTime, endTime, centreId);
        Map<String,Object> hourNumMap = new HashMap<>(32);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String,Object> item: list) {
                hourNumMap.put(String.valueOf(item.get("dayHour")), item.get("mNum"));
            }
        }
        while (calendar.getTime().before(endTime)) {
            Integer hour = calendar.get(Calendar.HOUR_OF_DAY);
            hList.add(hour+ "h");
            if (hourNumMap.get(String.valueOf(hour)) != null) {
                nList.add((Long) hourNumMap.get(String.valueOf(hour)));
            }else {
                nList.add(0L);
            }
            calendar.add(Calendar.HOUR_OF_DAY, 1);
        }
        Map<String,Object> result = new HashMap<>(4);
        result.put("centreId", centreId);
        result.put("hours", hList);
        result.put("nums", nList);
        return result;
    }

    @Override
    public Map<String, Object> getOrderTrend(Long centreId) {
        Calendar calendar = Calendar.getInstance();
        Date end = DateUtils.getDateEndTime(calendar.getTime());

        int max  = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DAY_OF_MONTH, - max);
        Date start = getDateStartTime(calendar.getTime());

        List<Map<String,Object>> trendList = orderProductMapper.getOrderTrend(start, end, centreId);
        Map<String,Object> dateNumMap = new HashMap<>(32);
        if (CollectionUtils.isNotEmpty(trendList)) {
            for (Map<String,Object> item: trendList) {
                dateNumMap.put((String) item.get("createDate"), item.get("orderNum"));
            }
        }

        List<String> days = new ArrayList<>();
        List<Long> orderNums = new ArrayList<>();
        int index = 0;
        while (index < calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            String day = DateUtils.format(calendar.getTime());
            days.add(day);

            if (dateNumMap.get(day) != null) {
                orderNums.add((Long) dateNumMap.getOrDefault(day,0L));
            }else {
                orderNums.add(0L);
            }
            index ++;
        }
        Map<String,Object> result = new HashMap<>(4);
        result.put("centreId", centreId);
        result.put("days", days);
        result.put("orderNums", orderNums);
        return result;
    }


}
